<template>
	<view>
		<u-popup v-model="vuex_login" mode="bottom" border-radius="14" :mask-close-able="false" @open="init">
			<view class="product-window">
				<view class="mp-data">
					<image :src="mpData.site_logo" mode=""></image>
					<text class="mp-name">{{mpData.site_name || ''}} 申请</text>
				</view>
				<view class="trip-msg">
					<view class="title">
						获取您的昵称、头像
					</view>
					<view class="trip">
						方便在本小程序中展示你的微信头像、昵称
					</view>
				</view>
				<form @submit="formSubmit">
					<view class="edit">
						<view class="avatar edit-box">
							<view class="left">
								<view class="head">头像</view>
								<view class="avatar-box" v-if="!mp_is_new" @click.stop='chooseImage'>
									<image :src="login.avatar || defHead"></image>
								</view>
								<button v-else class="avatar-box" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
									<image :src="login.avatar || defHead"></image>
								</button>
							</view>
						</view>
						<view class="nickname edit-box">
							<view class="left">
								<view class="head">昵称</view>
								<view class='input'><input type='nickname' placeholder-class="pl-sty"
										placeholder="未填写" name='nickname' :maxlength="16"
										:value='login.nickName'></input>
								</view>
							</view>
						</view>
						<view class="sex edit-box">
							<view class="left">
								<view class="head">性别</view>
								<view class='sex-input' v-for="(sex, index) in sexList" :key="index">
									<view @click="sexTab(index)" class="sex-span" :class="{'active': sexIndex == index}">{{sex.label}}</view>
								</view>
							</view>
						</view>
					</view>
					
					<!-- <view class="random-box">
						<uni-icons type="loop" color="#5b77ae" size="13"></uni-icons>
						<span class="label">随机头像与昵称</span>
					</view> -->
				
					<view class="bottom">
						<button class="close" @click="close">取消</button>
						<button class="save" formType="submit" :class="{'open': login.avatar}">
							保存
						</button>
					</view>
				</form>
			</view>
		</u-popup>
	</view>
</template>
<script>
	import {mapState} from 'vuex';
	const app = getApp();
	export default {
		name:'',
		props:{
			title:{
				type:String,
				default:'授权提示',
				
			},
			// 是否跳转
			isJump: {
				type: Boolean,
				default: true
			},
			content:{
				type:String,
				default:'申请获取用于完整服务',
			},
		},
		data() {
			return {
				login: {
					appId: '', 
					nickName: '',
					avatar: '',
					sex: '',
					encryptedData: '',
					code: '',
					phone: '',
					shareUserId: '',
					wxOpenId: '',
					anonymousCode: '',
					rawData: '',
					signature: '',
					iv: '',
					scene: '',
				},
				defHead: require('@/static/def_avatar.png'),
				mp_is_new:false, 
				mpData: {
					site_logo: require('@/static/logo.png'), 
					site_name: '晚趣'
				},
				form: {
					phone: '',
					code: '',
				},
				sexIndex: -1,
				sexList: [
					{
						label: '男',
						value: '0',
					},
					{
						label: '女',
						value: '1',
					},
				],
				check: false,
				disabled: true,
				loading: false,
			}
		},
		mounted() {
			this.mpData.site_name = this.website.appName;
			const version = uni.getSystemInfoSync().SDKVersion;
			if(this.compareVersion(version, '2.21.2') >= 0){
				this.mp_is_new = true;
			}
		},
		computed: {
			...mapState(['vuex_user']),
			vuex_login: {
			    get() {
			      return this.$store.state.vuex_login;
			    },
			    set(value) {
			      this.$store.commit('setLogin', value);
			    }
			},
		},
		methods:{
			init() {
				this.getUserProfile();
			},
			close() {
				this.$store.commit('setLogin', false);
			},
			// 微信头像获取
			onChooseAvatar(e) {
				const {
					avatarUrl
				} = e.detail
				this.updateAvatar(avatarUrl);
			},
			formSubmit(e) {
				if (!this.login.avatar) {
					this.$u.toast('请上传头像');
					return;
				}
				if (!e.detail.value.nickname) {
					this.$u.toast('请输入昵称');
					return;
				}
				if (!this.login.sex) {
					this.$u.toast('请选择性别');
					return;
				}
				this.login.nickName = e.detail.value.nickname;
				this.$u.post('/system/user/profile/edit', this.login).then(res => {
					if(this.isJump){
						this.close();
						uni.reLaunch({
						  url: '/pages/index'
						});
					}else{
						this.close();
					}
				});
			},
			//选照片 or 拍照
			chooseImage() {
				uni.chooseImage({
					count: 1, //默认9
					sourceType: ['album', 'camera'],
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					success: (res) => {
						for (let i = 0; i < res.tempFilePaths.length; i++) {
							uni.getImageInfo({
								src: res.tempFilePaths[i],
								success: (image) => {
									this.updateAvatar(image.path);
								}
							});
						}
					}
				});
			},
			updateAvatar(path) {
				var uploadAction = this.website.baseUrl + '/oss/oss/upload';
				uni.uploadFile({
					url: uploadAction,
					filePath: path,
					name: 'file',
					success: res => {
						var data = res.data;
						data = JSON.parse(data);
						if(data.code == 200){
							this.login.avatar = data.data;
						}else{
							this.$u.toast(data.msg);
						}
					},
					fail: e => {
						this.$u.toast('上传失败');
					}
				});
			},
			getPhoneCode(phone) {
				console.log(phone);
				this.form.phone = phone;
				this.$emit('getCode', phone);
			},
			codeChange(e) {
				console.log(e.code);
				if(e.code.length > 3){
					this.disabled = false;
				}else{
					this.disabled = true;
				}
				this.form.code = e.code;
			},
			sexTab(i) {
				this.sexIndex = i;
				this.login.sex = this.sexList[i].value;
			},
			toggleCheck() {
				if(this.check){
					this.check = false;
				}else{
					this.check = true;
				}
			},
			phoneLogin() {
				this.checkAggree();
			},
			checkAggree() {
				var _this = this;
				uni.showModal({
					title: '协议指引',
					content: '进入下一步前,请先阅读并同意相关用户协议',
					showCancel: true,
					confirmColor:'#333333',
					success:function (res){
						if (res.confirm) { 
							_this.check = true;
							_this.loading = true;
							_this.$emit('login', _this.form);
						}
					},
				})
			},
			/**
			 * 小程序比较版本信息
			 * @param v1 当前版本
			 * @param v2 进行比较的版本 
			 * @return boolen
			 * 
			 */
			compareVersion(v1, v2) {
				v1 = v1.split('.')
				v2 = v2.split('.')
				const len = Math.max(v1.length, v2.length)
			
				while (v1.length < len) {
					v1.push('0')
				}
				while (v2.length < len) {
					v2.push('0')
				}
			
				for (let i = 0; i < len; i++) {
					const num1 = parseInt(v1[i])
					const num2 = parseInt(v2[i])
			
					if (num1 > num2) {
						return 1
					} else if (num1 < num2) {
						return -1
					}
				}
				return 0
			},
			getUserProfile() {
				var token = uni.getStorageSync("token");
				if(!token){
					this.login.shareUserId = uni.getStorageSync("shareUserId");
					this.login.wxOpenId = uni.getStorageSync("wxOpenId");
					this.login.scene = uni.getStorageSync("scene");
					const _this = this;
					uni.login({
						provider: 'weixin',
						success: function(loginRes) {
							_this.login.code = loginRes.code;
							_this.login.appId = _this.website.appId;
							_this.$u.post('/auth/wx/login', _this.login).then(res => {
								uni.setStorageSync("userId", res.data.userId);
								var user = _this.vuex_user;
								user.userId = res.data.userId;
								_this.$store.commit('setUser', user);
								uni.setStorageSync("token", res.data.access_token);
								if(_this.isJump){
									//_this.close();
								}else{ 
									//_this.close();
								}
								
							});
						},
						fail: function() {
							
						}
					});
				}
			},
		}
	}
</script>

<style scoped lang="scss">
	.login-title {
		font-size: 28rpx;
		font-weight: bolder;
		display: flex;
		justify-content: center;
		padding-bottom: 20px;
	}
	.login-box {
		background-color: #fff;
		padding: 15px;
		border-top-left-radius: 10rpx;
		border-top-right-radius: 10rpx;
	}
	.aggre-box {
		margin-top: 30rpx;
		font-size: 20rpx;
		display: flex;
		align-items: center;
	}
	.wx-btn {
		font-size: 28rpx;
		color: #fff;
		padding: 6rpx;
	}
	.wx-btn::after {
		border: unset;
	}
	.check-box {
		margin-right: 5px;
	}
	.a-text {
		color: #81ea94dd;
	}
	.back-box {
		display: flex;
		align-items: center;
		padding: 30px 0px;
		position: relative;
	}
	.back-btn {
		background-color: #bbcabd;
		display: flex;
		justify-content: right;
		border-radius: 100%;
		width: 80rpx;
		height: 80rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		position: absolute;
		right: 0;
	}
	.uni-form-item {
		border-bottom: 1px solid #f9f0f0;
		font-weight: bolder;
		padding: 10px 0;
		margin-bottom: 20px;
	}
	.phone-box {
		margin-bottom: 15px;
	}
	
	
	.product-window.on {
		transform: translate3d(0, 0, 0);
	}
	
	.mask {
		z-index: 100;
	}
	
	.product-window {
		background-color: #fff;
		border-radius: 20rpx 20rpx 0 0;
		padding: 38rpx 40rpx;
		padding-bottom: 80rpx;
		padding-bottom: calc(80rpx+ constant(safe-area-inset-bottom)); ///兼容 IOS<11.2/
		padding-bottom: calc(80rpx + env(safe-area-inset-bottom)); ///兼容 IOS>11.2/
	
		.icon-guanbi {
			position: absolute;
			top: 30rpx;
			right: 30rpx;
			font-size: 24rpx;
			font-weight: bold;
			color: #999;
			padding: 10rpx;
		}
	
		.mp-data {
			display: flex;
			align-items: center;
			margin-bottom: 30rpx;
	
			.mp-name {
				font-size: 28rpx;
				font-weight: bold;
				color: #000000;
			}
	
			image {
				width: 48rpx;
				height: 48rpx;
				border-radius: 50%;
				margin-right: 16rpx;
			}
		}
	
		.trip-msg {
			padding-bottom: 32rpx;
			border-bottom: 1px solid #F5F5F5;
	
			.title {
				font-size: 30rpx;
				font-weight: bold;
				color: #000;
				margin-bottom: 12rpx;
			}
	
			.trip {
				font-size: 26rpx;
				color: #777777;
			}
		}
	
		.edit {
			border-bottom: 1px solid #F5F5F5;
	
			.avatar {
				border-bottom: 1px solid #F5F5F5;
			}
			
			.nickname {
				border-bottom: 1px solid #F5F5F5;
			}
	
			.nickname {
				.input {
					width: 100%;
	
				}
	
				input {
					height: 80rpx;
				}
			}
	
			.edit-box {
				display: flex;
				justify-content: space-between;
				align-items: center;
				font-size: 30rpx;
				padding: 22rpx 0;
	
				.left {
					display: flex;
					align-items: center;
					flex: 1;
	
					.head {
						color: rgba(0, 0, 0, 0.9);
						white-space: nowrap;
						margin-right: 60rpx;
					}
					
					.sex-input {
						display: flex;
						
						.active {
							border: 1px solid #07C160;
							background-color: #F5F5F5;
						}
					}
	
					button {
						display: flex;
						align-items: center;
						justify-content: center;
						width: 84rpx;
						height: 84rpx;
						border-radius: 6rpx;
						margin: unset;
						padding: unset;
						border: unset;
					}
				}
	
				image {
					width: 80rpx;
					height: 80rpx;
					border-radius: 6rpx;
				}
			}
	
			.icon-xiangyou {
				color: #cfcfcf;
			}
		}
		
		.random-box {
			display: flex;
			align-items: center;
			line-height: 100rpx;
			font-size: 26rpx;
			color: #5b77ae;
			
			.label {
				margin-left: 10px;
			}
		}
	
		.bottom {
			display: flex;
			align-items: center;
			justify-content: center;
			
			.close {
				display: flex;
				align-items: center;
				justify-content: center;
				width: 300rpx;
				height: 80rpx;
				border-radius: 12rpx;
				margin-top: 52rpx;
				background-color: #F5F5F5;
				color: #07C160;
				font-size: 30rpx;
				font-weight: bold;
			}
			
			.close::after {
				border: unset;
			}
			
			.save {
				border: unset;
				display: flex;
				align-items: center;
				justify-content: center;
				width: 300rpx;
				height: 80rpx;
				border-radius: 12rpx;
				margin-top: 52rpx;
				background-color: #F5F5F5;
				color: #ccc;
				font-size: 30rpx;
				font-weight: bold;
			}
			
			.save::after {
				border: unset;
			}
	
			.save.open {
				border: 1px solid #fff;
				background-color: #07C160;
				color: #fff;
			}
		}
	}
	.avatar-box {
		display: flex;
		align-items: center;
	
		image {
			width: 30rpx;
			height: 30rpx;
			border-radius: 50%;
		}
	}
	.sex-span {
		border: 1px solid #ddd;
		border-radius: 10px;
		padding: 10px 25px;
		margin-right: 10px;
		color: #07C160;
		font-size: 28rpx;
		font-weight: bolder;
		display: flex;
		justify-content: center;
		align-items: center;
	}
</style>